/**
 * @fileoverview 实现映射关系
 */
import * as _ from 'lodash';
import * as Mock from 'mockjs';
import * as primitives from './primitives';
export function genMockData(apiData) {
  if (!apiData || _.isEmpty(apiData)) {
    return {};
  }

  const result = {};
  for (let key in apiData) {
    result[key] = apiData[key];
    result[key].data = Mock.mock(apiData[key].example);
  }
  return result;
}

/**
 * 生成mock数据
 * @param obj
 * @returns {{}}
 */
export function parseObject(obj) {
  const example = {};
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (obj[key].type === 'object') {
        example[key] = parseObject(obj[key].properties || {});
      } else if (primitives[obj[key].type]) {
        example[key] = Mock.mock(primitives[obj[key].type]);
      } else if (obj[key].type === 'array') {
        const arr = [];
        for (let i = 0; i < Mock.mock('@integer(1,30)'); i++) {
          arr.push(parseObject(obj[key].items.properties || {}));
        }
        example[key] = arr;
      }
    }
  }
  return example;
}

export function parseRelations(result, relations) {
  if (_.isEmpty(relations)) {
    return result;
  }
  const { equals = {}, contains = {} } = relations;
  // 处理包含关系
  for (let path in contains) {
    var realPath = path.replace(/\.\$\{properties\}/g, '');
    var setValues = _.get(result, realPath);
    (contains[path].targets || []).forEach(item => {
      var targetPath = item.replace(/\.\$\{properties\}/g, '');
      // 包含类关系只适用于数组类型包含实体
      const randomIndex = Mock.mock(`@integer(0,${setValues.length})`);
      _.set(result, targetPath, setValues[randomIndex]);
    });
  }

  // 处理相等关系
  for (let path in equals) {
    var realPath = path.replace(/\.\$\{properties\}/g, '');
    var targetValue = _.get(result, realPath);
    (equals[path].targets || []).forEach(item => {
      var targetPath = item.replace(/\.\$\{properties\}/g, '');
      if (_.get(result, targetPath) !== undefined) {
        _.set(result, targetPath, targetValue);
      }
    });
  }
  return result;
}
interface Child {
  type: string;
  [key: string]: string;
}

export function convertObj2Tree(key, obj) {
  let children = [];
  for (let key in obj) {
    if (obj[key].type === 'object') {
      children = children.concat(
        convertObj2Tree(key, obj[key].properties || {})
      );
    } else {
      const tmp: Child = {
        type: '',
      };
      tmp.type = obj[key].type;
      tmp.key = key;
      tmp.title = key;
      children.push(tmp);
    }
  }
  return {
    key,
    children,
  };
}

export default function() {}
